package com.algorithm.Map;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * 当对遍历顺序没有要求，或者元素不具备可比较性的时候
 */
public class HashMap<K,V> implements Map<K,V>{
    private static final boolean RED = true;
    private static final boolean BLACK = false;
    private static final int DEFAULT_CAPACITY = 10;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
    private Node<K,V>[] table;
    private int size;

    public HashMap() {
        this.table = new Node[DEFAULT_CAPACITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        if (size == 0) return;
        for (int i = 0; i < table.length; i++) {
            table[i] = null;
        }
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        expandSize();
        int index = index(key);
        Node<K,V> node = table[index];
        if (node == null) {
            Node<K,V> newNode = createNode(key,value,null);
            table[index] = newNode;
            size++;
            afterPut(newNode);
            return null;
        }

        Node<K,V> parent;
        int cmp;
        int h1 = hash(key);
        Node<K, V> result = null;
        boolean search = false;
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                cmp = 1;
            }else if (h1 < h2) {
                cmp = -1;
            }else if (Objects.equals(key,k2)){
                cmp = 0;
            }else if (key != null && k2 != null
                    && key instanceof Comparable
                    && (cmp = ((Comparable) key).compareTo(k2)) != 0){
            } else if (search) {
                cmp = System.identityHashCode(key) - System.identityHashCode(k2);
            } else {
                if (node.left != null && (result = node(node.left,key)) != null
                        || node.right != null && (result = node(node.right,key)) != null) {
                    node = result;
                    cmp = 0;
                }else {
                    search = true;
                    cmp = System.identityHashCode(key) - System.identityHashCode(k2);
                }
            }

            if (cmp > 0) {
                node = node.right;
            }else if (cmp < 0) {
                node = node.left;
            }else {
                V oldValue = node.value;
                node.key = key;
                node.value = value;
                node.hash = h1;
                return oldValue;
            }
        }while (node != null);

        Node<K,V> newNode = createNode(key,value,parent);
        if (cmp > 0) {
            parent.right = newNode;
        }else {
            parent.left = newNode;
        }
        size++;
        afterPut(newNode);
        return null;
    }


    @Override
    public V get(K key) {
        Node<K,V> node = node(key);
        return  node == null ? null : node(key) .value;
    }

    @Override
    public V remove(K key) {
        Node<K,V> node = node(key);
        if (node == null) return null;
        Node<K,V> willNode = node;
        size--;
        V oldValue = node.value;

        if (node.hasTwoChild()) {
            Node<K,V> pre = successor(node);
            node.key = pre.key;
            node.value = pre.value;
            node.hash = pre.hash;
            node = pre;
        }

        Node<K,V> replaceNode = node.left != null ? node.left : node.right;
        int index = index(node);
        if (replaceNode != null) {
            replaceNode.parent = node.parent;
            if (node.parent == null) {
                table[index] = replaceNode;
            }else if (node.isLeftChild()) {
                node.parent.left = replaceNode;
            }else {
                node.parent.right = replaceNode;
            }
            fixAfterRemove(replaceNode);
        }else if (node.parent == null) {
            table[index] = null;
        }else {
            if (node.isLeftChild()) {
                node.parent.left = null;
            }else {
                node.parent.right = null;
            }
            fixAfterRemove(node);
        }
        afterRemove(willNode,node);
        return oldValue;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        for (Node<K, V> root : table) {
            if (root == null) continue;
            Queue<Node<K, V>> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (node.value.equals(value)) return true;

                if (node.left != null) {
                    queue.offer(node.left);
                }

                if (node.right != null) {
                    queue.offer(node.right);
                }
            }

        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {

    }

    /**
     * 扰动计算hash值
     */
    private int hash(K key) {
        if (key == null) return 0;
        int h = key.hashCode();
        return h ^ (h >>> 16);
    }

    private void expandSize() {
        if (size/table.length < DEFAULT_LOAD_FACTOR) return;
        Node<K,V>[] oldTable = table;
        table = new Node[table.length << 1];
        Queue<Node<K,V>> queue = new LinkedList<>();
        for (Node<K, V> root : oldTable) {
            if (root == null) continue;
            queue.offer(root);
            while (!queue.isEmpty()) {
                Node<K, V> node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }

                if (node.right != null) {
                    queue.offer(node.right);
                }
                moveNode(node);
            }
        }

        System.out.println("扩容为：" + table.length);
    }


    private void moveNode(Node<K,V> newNode) {
        //clear node
        newNode.left = null;
        newNode.right = null;
        newNode.parent = null;
        newNode.color = RED;

        int index = index(newNode);
        Node<K,V> node = table[index];
        if (node == null) {
            table[index] = newNode;
            afterPut(newNode);
            return;
        }

        int cmp = 0;
        Node<K,V> parent = node;
        while (node != null) {
            parent = node;
            int h1 = newNode.hash;
            int h2 = node.hash;
            if (h1 > h2) {
                cmp = 1;
            }else if (h1 < h2) {
                cmp = -1;
            }else if (newNode.key != null && node.key != null
                    && node.key.getClass() == newNode.key.getClass()
                    && newNode.key instanceof Comparable
                    && (cmp = ((Comparable) newNode.key).compareTo(node.key)) != 0){
            }else {
                cmp = System.identityHashCode(newNode.key) - System.identityHashCode(node.key);
            }

            if (cmp > 0) {
                node = node.right;
            }else {
                node = node.left;
            }
        }

        newNode.parent = parent;
        if (cmp > 0) {
            parent.right = newNode;
        }else {
            parent.left = newNode;
        }
        afterPut(newNode);
    }

    private int index(K key) {
        return hash(key) & (table.length -1);
    }

    private int index(Node<K,V> node) {
        if (node == null) return 0;
        return node.hash & (table.length-1);
    }

    private Node<K,V> node(K key) {
        Node<K,V> root = table[index(key)];
        return node(root,key);
    }

    private Node<K,V> node(Node<K, V> node, K k1) {
        int h1 = hash(k1);
        Node<K,V> result = null;
        int cmp;
        while (node != null) {
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                node = node.right;
            }else if (h1 < h2) {
                node = node.left;
            }else if (Objects.equals(k1,k2)){
                return node;
            }else if (k1 != null && k2 != null
                    && k1 instanceof  Comparable
                    && k1.getClass() == k2.getClass()
                    && (cmp = ((Comparable) k1).compareTo(k2)) != 0){
                node = cmp > 0 ? node.right : node.left;
            }else if (node.right != null && (result = node(node.right,k1)) != null) {
                return result;
            }else {
                node = node.left;
            }
        }
        return null;
    }

    private Node<K,V> successor(Node<K,V> node) {
        if (node == null) return null;
        Node<K,V> p = node.right;
        if (p != null){
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }

        while (node.parent != null && node.parent.right == node) {
            node = node.parent;
        }
        return node.parent;
    }

    private void afterPut(Node<K,V> node) {
        Node<K,V> parent = node.parent;
        if (parent == null) {
            black(node);
            return;
        }

        if (isBlack(parent)) return;

        Node<K,V> uncle = parent.sibling();
        Node<K,V> grand = red(parent.parent);
        if (isRed(uncle)) {//r-b-r 需要溢出
            black(parent);
            black(uncle);
            afterPut(grand);
            return;
        }

        if (parent.isLeftChild()) {
            if (node.isLeftChild()) {
                black(parent);
            }else {
                black(node);
                rotatingLeft(parent);
            }
            rotatingRight(grand);
        }else {
            if (node.isLeftChild()) {
                black(node);
                rotatingRight(parent);
            }else {
                black(parent);
            }
            rotatingLeft(grand);
        }
    }

    private void fixAfterRemove(Node<K,V> node) {
        if (isRed(node)) {
            black(node);
            return;
        }

        Node<K,V> parent = node.parent;
        if (parent == null) return;

        boolean left = parent.left == null || node.isLeftChild();
        Node<K,V> sibling = left ? parent.right : parent.left;
        if (left) {
            if (isRed(sibling)) {
                red(parent);
                black(sibling);
                rotatingLeft(parent);
                sibling = parent.right;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean bNeedRet = isBlack(parent);
                red(sibling);
                black(parent);
                if (bNeedRet) {
                    fixAfterRemove(parent);
                }
            }else {
                if (isBlack(sibling.right)) {
                    rotatingRight(sibling);
                    sibling = parent.right;
                }
                color(sibling,colorOf(parent));
                black(parent);
                black(sibling.right);
                rotatingLeft(parent);
            }
        }else {
            if (isRed(sibling)) {
                red(parent);
                black(sibling);
                rotatingRight(parent);
                sibling = parent.left;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean bNeedRet = isBlack(parent);
                red(sibling);
                black(parent);
                if (bNeedRet) {
                    fixAfterRemove(parent);
                }
            }else {
                if (isBlack(sibling.left)) {
                    rotatingLeft(sibling);
                    sibling = parent.left;
                }
                color(sibling,colorOf(parent));
                black(parent);
                black(sibling.left);
                rotatingRight(parent);
            }
        }
    }

    protected void afterRemove(Node<K,V> willNode,Node<K,V> remvoeNode) {}

    private void rotatingLeft(Node<K,V> grand) {
        Node<K,V> parent = grand.right;
        Node<K,V> child = parent.left;

        grand.right = child;
        parent.left = grand;
        afterRotating(grand,parent,child);
    }

    private void rotatingRight(Node<K,V> grand) {
        Node<K,V> parent = grand.left;
        Node<K,V> child = parent.right;

        grand.left = child;
        parent.right = grand;
        afterRotating(grand,parent,child);
    }

    private void afterRotating(Node<K,V> grand, Node<K,V> parent, Node<K,V> child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            parent.parent.left = parent;
        }else if (grand.isRightChild()) {
            parent.parent.right = parent;
        }else {
            int index = index(grand.key);
            table[index] = parent;
        }

        if (child != null) {
            child.parent = grand;
        }
        grand.parent = parent;
    }

    protected Node<K,V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key,value,parent);
    }

    private boolean colorOf(Node<K,V> node) {
        return node == null ? BLACK : node.color;
    }

    private boolean isRed(Node<K,V> node) {
        return colorOf(node) == RED;
    }

    private boolean isBlack(Node<K,V> node) {
        return colorOf(node) == BLACK;
    }

    private Node<K,V> color(Node<K,V> node,boolean color) {
        if (node == null) return null;
        node.color = color;
        return node;
    }

    private Node<K,V> red(Node<K,V> node) {
        return color(node, RED);
    }

    private Node<K,V> black(Node<K,V> node) {
        return color(node,BLACK);
    }

    protected static class Node<K,V> {
        K key;
        V value;
        int hash;
        boolean color = RED;
        Node<K,V> left;
        Node<K,V> right;
        Node<K,V> parent;

        Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
            int hashCode = key == null ? 0 : key.hashCode();
            this.hash = hashCode ^ (hashCode >>> 16);
        }

        boolean hasTwoChild() {
            return left != null && right != null;
        }

        boolean isLeftChild() {
            return parent != null && parent.left == this;
        }

        boolean isRightChild() {
            return parent != null && parent.right == this;
        }

        Node<K,V> sibling() {
            if (parent == null) return null;
            if (isLeftChild()) return parent.right;
            if (isRightChild()) return parent.left;
            return null;
        }
    }
}
